import { _decorator, Component, Label, Node, Color, Sprite } from 'cc';
import { SelectLevelPanelController } from './SelectLevelPanelController';
const { ccclass, property } = _decorator;

@ccclass('LevelItem')
export class LevelItem extends Component {
    @property(Label)
    levelLabel: Label = null;

    private level: number = 0;
    private isSelected: boolean = false;

    // 定义选中和未选中的颜色
    private readonly NORMAL_COLOR = new Color(255, 255, 255, 255);
    private readonly SELECTED_COLOR = new Color(255, 255, 0, 255);

    start() {
        this.node.on(Node.EventType.TOUCH_START, this.onClicked, this);
        this.updateVisual();
    }

    setLabel(level: number) {
        this.level = level;
        this.levelLabel.string = `Level ${level}`;
    }

    getLevel(): number {
        return this.level;
    }

    setSelected(selected: boolean) {
        this.isSelected = selected;
        this.updateVisual();
    }

    private updateVisual() {
        // 更新选中状态的视觉效果
        const color = this.isSelected ? this.SELECTED_COLOR : this.NORMAL_COLOR;
        this.node.getComponent(Sprite).color = color;
    }

    private onClicked() {
        const selectLevelPanel = this.node.parent.parent.parent.parent;
        if (!selectLevelPanel) {
            console.error('SelectLevelPanel node not found!');
            return;
        }

        const controller = selectLevelPanel.getComponent(SelectLevelPanelController);
        if (controller) {
            controller.onLevelSelected(this.level);
        } else {
            console.error('SelectLevelPanelController not found!');
        }
    }

    onDestroy() {
        this.node.off(Node.EventType.TOUCH_START, this.onClicked, this);
    }
}


